<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    div{
        width: 200px;
        height: 200px;
        background: cadetblue;
        position: absolute;
    }
    </style>
</head>
<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>

    <script>
        var boxlist=document.getElementsByTagName("div");
        for(var i=0;i<boxlist.length;i++){
              boxlist[i].onmousedown=function(e){
                var e=e||window.event
                var box_x=e.offsetX;
                var box_y=e.offsetY;
                var that=this;
                document.onmousemove=function(e){
                    that.style.left=e.pageX-box_x+"px"
                    that.style.top=e.pageY-box_y+"px"
                    if(e.pageX-box_x<=0){
                        that.style.left=0
                    }
                    if(e.pageY-box_y<=0){
                        that.style.top=0
                    }
                    if(e.pageX-box_x>=maxwidth){
                        that.style.left=maxwidth+"px"
                    }
                    if(e.pageY-box_y>=maxheight){
                        that.style.top=maxheight+"px"
                    }   
                }
                document.onmouseup=function(){
                    document.onmousemove=null;
                    return false
                }
                }

              }



    // 鼠标跟随
    // document.onmousemove=function(e){
    //       box.style.left=e.pageX-box.clientWidth/2+"px"
    //       box.style.top=e.pageY-box.clientHeight/2+"px"
    //       var maxwidth=window.innerWidth-box.clientWidth;
    //       var maxheight=window.innerHeight-box.clientHeight;
    //     if(e.pageX-box.clientWidth/2<=0){
    //         box.style.left=0
    //     }
    //     if(e.pageY-box.clientHeight/2<=0){
    //         box.style.top=0
    //     }
    //     if(e.pageX-box.clientWidth/2>=maxwidth){
    //         box.style.left=maxwidth+"px"
    //     }
    //     if(e.pageY-box.clientHeight/2>=maxheight){
    //         box.style.top=maxheight+"px"
    //     }
    // }
    </script>
</body>
</html>